<script setup>
import {ref, onMounted} from 'vue'
import {ElCard, ElTable, ElTableColumn, ElMessage,ElMessageBox} from 'element-plus'
import {
  getConsumablesCategoryList,
  addConsumablesCategory,
  getConsumablesCategoryTree,
  deleteConsumablesCategory,
  getConsumablesCategoryDetail,
  updateConsumablesCategory
} from "@/api/ConsumablesCategory.js"

import {Search, Plus, Refresh, Edit, Delete} from '@element-plus/icons-vue'


// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 分类表单数据
const categoryForm = ref({
  name: '',
  parentId: null
})

// 分类树形数据
const parentCategories = ref([])

// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的分类ID
const currentCategoryId = ref(null)

// 表单验证规则
const rules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'}
  ]
}

// 获取耗材分类树形数据
const getConsumablesCategoryTreeData = () => {
  getConsumablesCategoryTree({
    name: queryForm.value.name
  }).then(res => {
    if (res.code === 200) {
      parentCategories.value = res.data
    }
  })
}

// 提交分类表单
const handleSubmit = () => {
  console.log(categoryForm.value, 789)

  // 检查分类名称是否为空
  if (!categoryForm.value.name) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  const apiMethod = isEditMode.value
      ? updateConsumablesCategory
      : addConsumablesCategory;

  const requestData = {
    id: currentCategoryId.value,
    name: categoryForm.value.name,
    parentId: categoryForm.value.parentId
  };

  apiMethod(requestData).then(res => {
    if (res.code === 200) {
      ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
      formVisible.value = false;
      resetForm();
      getConsumablesCategoryTreeData();
    }
  });
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  currentCategoryId.value = null;
  categoryForm.value = {name: '', parentId: null};
}

// 新增耗材分类
const addConsumablesCategoryData = () => {
  resetForm()
  formVisible.value = true
  title.value = '新增分类'
}

// 删除耗材分类
const deleteConsumablesCategoryData = (row) => {
  //console.log(row, "删除")
  ElMessageBox.confirm( '确定删除该耗材类别信息吗?',  '系统警告',    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteConsumablesCategory(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getConsumablesCategoryTreeData()
      }
    }).catch(err => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    console.log('取消删除')
  })


}

// 编辑耗材分类
const editConsumablesCategoryData = (row) => {
  title.value = '编辑分类'
  // 根据id获取分类详情
  getConsumablesCategoryDetail(row.id).then(res => {
    if (res.code === 200) {
      isEditMode.value = true;
      currentCategoryId.value = row.id;
      categoryForm.value = {
        name: res.data.name,
        parentId: res.data.parentId
      }
      formVisible.value = true
    }
  })
}

// 搜索框绑定的分类名称
const queryForm = ref({
  name: ''
})

// 按分类名称搜索的方法
const handleSearch = () => {
  // 判断是否为空
  if (!queryForm.value.name) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  getConsumablesCategoryTreeData()
}

// 重置搜索条件
const handleReset = () => {
  queryForm.value.name = ''
  getConsumablesCategoryTreeData()
}

onMounted(() => {
  getConsumablesCategoryTreeData()
})
</script>


<template>

  <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="margin:10px 0 0 0;">
    <el-form-item>
      <el-space>
        <el-input v-model="queryForm.name" placeholder="请输入分类名称" clearable style="width: 300px"
                  :prefix-icon="Search">
          <template #append>
            <el-button type="primary" :icon="Search" :style="$globalAttribute.primaryButton" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" :icon="Refresh" plain @click="handleReset">
          重置
        </el-button>
        <el-button plain type="primary" :icon="Plus" @click="addConsumablesCategoryData">
          新增
        </el-button>
      </el-space>
    </el-form-item>
  </el-form>
  <el-dialog v-model="formVisible" :title="title" width="30%">
    <el-form :model="categoryForm" :rules="rules" label-width="100px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="categoryForm.name" clearable/>
      </el-form-item>
      <el-form-item label="上级分类">
        <el-cascader
            v-model="categoryForm.parentId"
            :options="parentCategories"
            :props="{
                      value: 'id',
                      label: 'name',
                      children: 'children',
                      checkStrictly: true, // 启用任意节点选择
                      emitPath: false
                    }"
            placeholder="请选择上级分类"
            clearable
            :show-all-levels="false"
            popper-class="cascader-popper"
        />
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-table
      :data="parentCategories"
      table-layout="auto"
      height="80%"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

    <el-table-column prop="name" label="分类名称" align="left"/>
    <!--    <el-table-column prop="createTime" label="创建时间" align="center" width="200"/>-->
    <el-table-column label="操作" align="center" width="200">
      <template #default="scope">
        <el-space>
          <el-link type="primary" :icon="Edit" @click="editConsumablesCategoryData(scope.row)">
            修改
          </el-link>
          <el-link type="danger" :icon="Delete" @click="deleteConsumablesCategoryData(scope.row)">
            删除
          </el-link>
        </el-space>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;

    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}
</style>